import entity.Score;
import entity.Student;
import gui.MainFrame;
import service.FileManager;
import service.ScoreAnalysis;
import service.ScoreManager;
import service.StudentManager;
import utils.*;

import javax.swing.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.Map;

public class MainSystem {
    private static final ScoreManager scoreManager = new ScoreManager();
    private static final StudentManager studentManager = new StudentManager();
    private static final FileManager fileManager = new FileManager();
    private static final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8);
    private static final ScannerUtil scannerUtil = new ScannerUtil(scoreManager, studentManager);

    public static void main(String[] args) {
        // 设置Swing的外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 启动模式选择
        String[] options = {"图形界面", "命令行界面"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择启动模式",
                "学生管理系统",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);
        
        if (choice == 0) {
            // 图形界面模式
            SwingUtilities.invokeLater(() -> {
                MainFrame mainFrame = new MainFrame(scoreManager, studentManager, fileManager);
                mainFrame.setVisible(true);
            });
        } else {
            // 命令行模式
            runConsoleMode();
        }
    }
    
    /**
     * 运行命令行模式
     */
    private static void runConsoleMode() {
        while (true) {
            showMainMenu();
            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    studentInfoMenu();
                    break;
                case "2":
                    scoreMenu();
                    break;
                case "3":
                    statisticsMenu();
                    break;
                case "4":
                    dataMenu();
                    break;
                case "5":
                    System.out.println("系统已退出，再见！");
                    return;
                default:
                    System.out.println("无效选项，请重新输入。");
            }
        }
    }

    private static void showMainMenu() {
        System.out.println("\n=== 学生管理系统 ===");
        System.out.println("1. 学生信息管理");
        System.out.println("2. 成绩管理");
        System.out.println("3. 统计分析");
        System.out.println("4. 数据管理");
        System.out.println("5. 退出系统");
        System.out.print("请选择功能编号：");
    }

    private static void studentInfoMenu() {
        System.out.println("\n-- 学生信息管理 --");
        System.out.println("1. 添加学生");
        System.out.println("2. 删除学生");
        System.out.println("3. 修改学生信息");
        System.out.println("4. 查询学生信息");
        System.out.println("5. 显示全部学生信息");
        System.out.print("请选择操作编号：");
        String input = scanner.nextLine();
        switch (input) {
            case "1":
                scannerUtil.addStudentWithValidation();
                break;
            case "2":
                System.out.print("请输入要删除的学号：");
                String delId = scanner.nextLine();
                studentManager.deleteStudent(delId);
                break;
            case "3":
                scannerUtil.updateStudentWithValidation();
                break;
            case "4":
                System.out.print("请输入要查询的学号：");
                String queryId = scanner.nextLine();
                Student stu = studentManager.getStudentById(queryId);
                if (stu != null) {
                    System.out.println(stu);
                }
                break;
            case "5":
                studentManager.showStudents();
                break;
            default:
                System.out.println("无效选项！");
        }
    }

    private static void scoreMenu() {
        System.out.println("\n-- 成绩管理 --");
        System.out.println("1. 录入成绩");
        System.out.println("2. 修改成绩");
        System.out.println("3. 删除成绩记录");
        System.out.println("4. 查询学生成绩");
        System.out.println("5. 显示所有成绩");
        System.out.print("请选择操作编号：");
        String input = scanner.nextLine();
        switch (input) {
            case "1":
                scannerUtil.addScoreWithValidation();
                break;
            case "2":
                scannerUtil.updateScoreWithValidation();
                break;
            case "3":
                System.out.print("请输入要删除成绩的学号：");
                String delScoreId = scanner.nextLine();
                scoreManager.deleteScore(delScoreId);
                break;
            case "4":
                System.out.print("请输入要查询成绩的学号：");
                String queryScoreId = scanner.nextLine();
                Score score = scoreManager.getScoreById(queryScoreId);
                if (score != null) {
                    System.out.println(score);
                }
                break;
            case "5":
                scoreManager.showScores();
                break;
            default:
                System.out.println("无效选项！");
        }
    }

    private static void statisticsMenu() {
        // 每次进入都重新分析，保证数据实时
        ScoreAnalysis scoreAnalysis = new ScoreAnalysis(scoreManager.getScores());
        System.out.println("\n-- 统计分析 --");
        System.out.println("1. 班级成绩平均分");
        System.out.println("2. 学生成绩排名");
        System.out.println("3. 成绩分布分析");
        System.out.print("请选择操作编号：");
        String input = scanner.nextLine();
        switch (input) {
            case "1":
                System.out.printf("语文平均分：%.2f\n", scoreAnalysis.averageChinese());
                System.out.printf("数学平均分：%.2f\n", scoreAnalysis.averageMath());
                System.out.printf("英语平均分：%.2f\n", scoreAnalysis.averageEnglish());
                break;
            case "2":
                scoreAnalysis.printScoresRanking(studentManager);
                break;
            case "3":
                scoreAnalysis.analyzeScoreDistribution();
                break;
            default:
                System.out.println("无效选项！");
        }
    }

    private static void dataMenu() {
        System.out.println("\n-- 数据管理 --");
        System.out.println("1. 保存学生数据到文件");
        System.out.println("2. 保存成绩数据到文件");
        System.out.println("3. 从文件加载学生数据");
        System.out.println("4. 从文件加载成绩数据");
        System.out.println("5. 备份数据");
        System.out.print("请选择操作编号：");
        String input = scanner.nextLine();
        switch (input) {
            case "1":
                fileManager.saveStudent(studentManager.getStudentMap());
                break;
            case "2":
                fileManager.saveScore(scoreManager.getScores());
                break;
            case "3":
                Map<String, Student> loadedStudents = fileManager.loadStudents();
                // 将加载的数据赋值给studentManager
                studentManager.getStudentMap().clear(); // 清空现有数据
                studentManager.getStudentMap().putAll(loadedStudents); // 添加加载的数据
                break;
            case "4":
                Map<String, Score> loadedScores = fileManager.loadScores();
                // 将加载的数据赋值给studentManager
                scoreManager.getScores().clear(); // 清空现有数据
                scoreManager.getScores().putAll(loadedScores); // 添加加载的数据
                break;
            case "5":
                fileManager.saveBackup();
                break;
            default:
                System.out.println("无效选项！");
        }
    }

}